package io.cici.server.common.module;


import io.cici.common.model.SystemMetrics;
import io.cici.common.request.WorkerHeartbeatRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


/**
 * @author huihui
 */
@Data
@Slf4j
public class WorkerInfo {

    private static final long WORKER_TIMEOUT_MS = 60000;
    private String address;
    private long lastActiveTime;
    private String protocol;
    private String client;
    private String tag;
    private int lightTaskTrackerNum;
    private int heavyTaskTrackerNum;
    private long lastOverloadTime;
    private boolean overloading;
    private SystemMetrics systemMetrics;

    public void refresh(WorkerHeartbeatRequest request) {
        address = request.getWorkerAddress();
        lastActiveTime = request.getHeartbeatTime();
        protocol = request.getProtocol();
        client = request.getClient();
        tag = request.getTag();
        systemMetrics = request.getSystemMetrics();


        lightTaskTrackerNum = request.getLightTaskTrackerNum();
        heavyTaskTrackerNum = request.getHeavyTaskTrackerNum();

        if (request.isOverload()) {
            overloading = true;
            lastOverloadTime = request.getHeartbeatTime();
            log.warn("[WorkerInfo] worker {} is overload!", getAddress());
        } else {
            overloading = false;
        }
    }

    public boolean timeout() {
        long timeout = System.currentTimeMillis() - lastActiveTime;
        return timeout > WORKER_TIMEOUT_MS;
    }

    public boolean overload() {
        return overloading;
    }
}
